//
//  BrandCustom.m
//  cutter
//
//  Created by mac on 16/1/20.
//  Copyright © 2016年 e360. All rights reserved.
//
#import "TMGlobal.h"
#import "TMCategory.h"
#import "AppData+User.h"

@implementation AppData (User)
//
+(id)userClientDeleteGroup:(id)data{
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM e360_user WHERE groupid='%@'", [data objectForKey:@"uuid"]];
    NSArray *clients = [[TMSQLite shareInstance] query:sql];
    for (id client in clients) {
        [self userDeleteClient:client];
    }
    //
    if (NO == [self cacheData:data table:@"e360_user_group" key:@"uuid" type:0]) {
        NSString *url = [NSString stringWithFormat:@"?n=api&a=user&c=user&m=del_client_group&uuid=%@", [data objectForKey:@"uuid"]];
        if ([self loadJson:url key:@"data" data:nil]) {
            return data;
        }else{
            return nil;
        }
    }
    return data;
}
+(id)userClientEditGroup:(id)data{
    if (NO == [self cacheData:data table:@"e360_user_group" key:@"uuid" type:1]) {
        NSMutableDictionary *temp = [NSMutableDictionary dictionary];
        [temp setValue:[data objectForKey:@"groupname"] forKey:@"groupname"];
        [temp setValue:[data objectForKey:@"sort"] forKey:@"sort"];
        [temp setValue:[data objectForKey:@"uuid"] forKey:@"uuid"];
        if ([self loadJson:@"?n=api&a=user&c=user&m=save_client_group" key:@"data" data:temp]) {
            return data;
        }else{
            return nil;
        }
    }
    return data;
}
+(id)userClientGroup:(id)user{
    if ([[UIDevice currentDevice] network] != UIDeviceNetworkNone) {
        [[TMSQLite shareInstance] query:@"DELETE FROM e360_user WHERE parentid>0"];
        [[TMSQLite shareInstance] query:@"DELETE FROM e360_user_group"];
        //
        NSArray *group = [self loadJson:@"?n=api&a=user&c=user&m=client_group" key:@"data" data:nil];
        NSArray *client = [self loadJson:@"?n=api&a=user&c=user&m=client&groupid=" key:@"data" data:nil];
        if (group || client) {
            [[[TMSQLite shareInstance] transaction] begin];
            for (id item in group) {
                NSString *sql = [self fromInsert:@"e360_user_group" data:item];
                [[TMSQLite shareInstance] query:sql];
            }
            for (id item in client) {
                NSString *sql = [self fromInsert:@"e360_user" data:item];
                [[TMSQLite shareInstance] query:sql];
            }
            [[[TMSQLite shareInstance] transaction] commit];
        }
    }
    //
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM e360_user_group WHERE deleted=0 AND userid=%@ ORDER BY sort", [user objectForKey:@"id"]];
    return [[TMSQLite shareInstance] query:sql];
}
//
+(id)userDeleteClient:(id)data{
    if (NO == [self cacheData:data table:@"e360_user" key:@"uuid" type:0]) {
        NSString *url = [NSString stringWithFormat:@"?n=api&a=user&c=user&m=del_client&uuid=%@", [data objectForKey:@"uuid"]];
        if ([self loadJson:url key:@"data" data:nil]) {
            return data;
        }else{
            return nil;
        }
    }
    return data;
}
+(id)userEditClient:(id)data{
    if (NO == [self cacheData:data table:@"e360_user" key:@"uuid" type:1]) {
        NSMutableDictionary *temp = [NSMutableDictionary dictionary];
        [temp setValue:[data objectForKey:@"groupid"] forKey:@"groupid"];
        [temp setValue:[data objectForKey:@"address"] forKey:@"address"];
        [temp setValue:[data objectForKey:@"province"] forKey:@"province"];
        [temp setValue:[data objectForKey:@"truename"] forKey:@"truename"];
        [temp setValue:[data objectForKey:@"mobile"] forKey:@"mobile"];
        [temp setValue:[data objectForKey:@"email"] forKey:@"email"];
        [temp setValue:[data objectForKey:@"city"] forKey:@"city"];
        [temp setValue:[data objectForKey:@"area"] forKey:@"area"];
        [temp setValue:[data objectForKey:@"uuid"] forKey:@"uuid"];
        [temp setValue:[data objectForKey:@"id"] forKey:@"id"];
        if ([self loadJson:@"?n=api&a=user&c=user&m=save_client" key:@"data" data:temp]) {
            return data;
        }else{
            return nil;
        }
    }
    return data;
}
+(id)userClient:(id)data user:(id)user{
    NSString *u = [NSString stringWithFormat:@"%@ AS userid", [user objectForKey:@"id"]];
    NSString *c = @"(SELECT areaname FROM e360_area WHERE id=e360_user.city) AS cityname";
    NSString *a = @"(SELECT areaname FROM e360_area WHERE id=e360_user.area) AS areaname";
    NSString *p = @"(SELECT areaname FROM e360_area WHERE id=e360_user.province) AS provincename";
    //
    id keyword = [data objectForKey:@"keyword"];
    if (keyword && user) {
        NSString *sql = [NSString stringWithFormat:@"SELECT *, %@, %@, %@, %@ FROM e360_user WHERE deleted=0 AND parentid=%@", p, c, a, u, [user objectForKey:@"id"]];
        if (keyword) {
            sql = [sql stringByAppendingFormat:@" AND (username LIKE '%%%@%%' OR truename LIKE '%%%@%%' OR mobile LIKE '%%%@%%')", keyword, keyword, keyword];
        }
        NSArray *items = [[TMSQLite shareInstance] query:sql];
        for (id item in items) {
            sql = [NSString stringWithFormat:@"SELECT * FROM e360_user_group WHERE deleted=0 AND uuid='%@'", [item objectForKey:@"groupid"]];
            [item setValue:[[[TMSQLite shareInstance] query:sql] firstObject] forKey:@"group"];
        }
        return items;
    }
    //
    NSString *sql = [NSString stringWithFormat:@"SELECT *, %@, %@, %@, %@ FROM e360_user WHERE deleted=0 AND groupid='%@'", p, c, a, u, [data objectForKey:@"uuid"]];
    NSArray *items = [[TMSQLite shareInstance] query:sql];
    for (id item in items) {
        [item setValue:data forKey:@"group"];
    }
    return items;
}
+(id)userClientDetail:(id)uuid{
    id user = [TMGlobal valueForKey:@"user"];
    NSString *u = [NSString stringWithFormat:@"%@ AS userid", [user objectForKey:@"id"]];
    NSString *c = @"(SELECT areaname FROM e360_area WHERE id=e360_user_client.city) AS cityname";
    NSString *a = @"(SELECT areaname FROM e360_area WHERE id=e360_user_client.area) AS areaname";
    NSString *p = @"(SELECT areaname FROM e360_area WHERE id=e360_user_client.province) AS provincename";
    NSString *sql = [NSString stringWithFormat:@"SELECT *, %@, %@, %@, %@ FROM e360_user_client WHERE deleted=0 AND uuid='%@'", p, c, a, u, uuid];
    return [[[TMSQLite shareInstance] query:sql] firstObject];
}
//
+(id)userDeleteCart:(id)data{
    if (NO == [self cacheData:data table:@"e360_cart" key:@"uuid" type:0]) {
        NSMutableArray *temps = [NSMutableArray array];
        if ([data isKindOfClass:NSArray.class]) {
            for (id item in data) {
                if ([item isKindOfClass:NSDictionary.class]) {
                    [temps addObject:item];
                }
            }
        }
        if ([data isKindOfClass:NSDictionary.class]) {
            [temps addObject:data];
        }
        //
        NSMutableArray *uuid = [NSMutableArray array];
        for (id item in temps) {
            id iid = [item objectForKey:@"uuid"];
            if (iid) {
                [uuid addObject:iid];
            }
        }
        NSString *url = [NSString stringWithFormat:@"?n=api&a=user&c=cart&m=del&uuid=%@", [uuid componentsJoinedByString:@","]];
        if ([self loadJson:url key:nil data:nil]) {
            return data;
        }else{
            return nil;
        }
    }
    return data;
}
+(id)userEditCart:(id)data{
    if (NO == [self cacheData:data table:@"e360_cart" key:@"uuid" type:1]) {
        NSMutableDictionary *temp = [NSMutableDictionary dictionary];
        [temp setValue:[data objectForKey:@"number"] forKey:@"count"];
        [temp setValue:[data objectForKey:@"uuid"] forKey:@"uuid"];
        //
        NSString *url = @"?n=api&a=user&c=cart&m=number";
        for (id key in temp) {
            id val = [temp objectForKey:key];
            if (val && val != [NSNull null]) {
                url = [url stringByAppendingFormat:@"&%@=%@", key, val];
            }else{
                url = [url stringByAppendingFormat:@"&%@=", key];
            }
        }
        if ([self loadJson:url key:nil data:temp]) {
            return data;
        }else{
            return nil;
        }
    }
    return data;
}
+(id)userAddCart:(id)data client:(id)client{
    NSMutableArray *temps = [NSMutableArray array];
    if ([data isKindOfClass:NSArray.class]) {
        for (id item in data) {
            if ([item isKindOfClass:NSDictionary.class]) {
                [temps addObject:item];
            }
        }
    }
    if ([data isKindOfClass:NSDictionary.class]) {
        [temps addObject:data];
    }
    //
    NSMutableArray *post = [NSMutableArray array];
    NSMutableArray *cache = [NSMutableArray array];
    for (id temp in temps) {
        id number = [temp objectForKey:@"number"];
        if(number == nil){
            number = [temp objectForKey:@"count"];
        }
        if(number == nil){
            number = [temp objectForKey:@"productcount"];
        }
        if(number == nil) {
            number = [NSNumber numberWithInt:1];
        }
        //
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM e360_cart WHERE deleted=0 AND productid=%@", [temp objectForKey:@"id"]];
        if ([client objectForKey:@"uuid"]) {
            sql = [sql stringByAppendingFormat:@" AND clientuuid='%@'", [client objectForKey:@"uuid"]];
        }
        if ([temp objectForKey:@"matchid"]) {
            sql = [sql stringByAppendingFormat:@" AND matchid=%@", [temp objectForKey:@"matchid"]];
        }
        if ([temp objectForKey:@"suitid"]) {
            sql = [sql stringByAppendingFormat:@" AND suitid=%@", [temp objectForKey:@"suitid"]];
        }
        //
        id old = [[[TMSQLite shareInstance] query:sql] firstObject];
        if (old) {
            NSInteger count = [[old objectForKey:@"number"] integerValue] + [number integerValue];
            [old setValue:[NSNumber numberWithInteger:count] forKey:@"number"];
            [cache addObject:old];
            //
            NSMutableDictionary *iii = [NSMutableDictionary dictionaryWithDictionary:old];
            [iii setValue:number forKey:@"number"];
            [iii setValue:nil forKey:@"id"];
            [post addObject:iii];
        }else{
            id uuid = [NSString uuid];
            id hardpacked = [temp objectForKey:@"temp_hardpacked"];
            if (hardpacked == nil) {
                hardpacked = [temp objectForKey:@"hardpacked"];
            }
            //
            NSMutableDictionary *iii = [NSMutableDictionary dictionary];
            [iii setValue:[client objectForKey:@"uuid"] forKey:@"clientuuid"];
            [iii setValue:[temp objectForKey:@"matchid"] forKey:@"matchid"];
            [iii setValue:[temp objectForKey:@"suitid"] forKey:@"suitid"];
            [iii setValue:[temp objectForKey:@"id"] forKey:@"productid"];
            [iii setValue:[temp objectForKey:@"json"] forKey:@"json"];
            [iii setValue:hardpacked forKey:@"hardpacked"];
            [iii setValue:number forKey:@"number"];
            [iii setValue:uuid forKey:@"uuid"];
            [cache addObject:iii];
            [post addObject:iii];
        }
    }
    //
    if (NO == [self cacheData:cache table:@"e360_cart" key:@"uuid" type:1]) {
        NSMutableDictionary *temp = [NSMutableDictionary dictionary];
        [temp setValue:[TMJSON stringify:post] forKey:@"productarr"];
        //
        if ([self loadJson:@"?n=api&a=user&c=cart&m=add_products" key:@"data" data:temp]) {
            return data;
        }else{
            return nil;
        }
    }
    return data;
}
+(id)userCart:(id)data{
    if ([[UIDevice currentDevice] network] != UIDeviceNetworkNone) {
        NSString *url = [NSString stringWithFormat:@"?n=api&a=user&c=cart&m=index&clientuuid=%@", (data ? [data objectForKey:@"uuid"] : @"")];
        NSMutableDictionary *items = [self loadJson:url key:@"data" data:nil];
        if (items) {
            [[[TMSQLite shareInstance] transaction] begin];
            //
            NSArray *products = [items objectForKey:@"product"];
            if(isEmpty(products)==NO) {
                NSString *sql = [self fromDelete:@"e360_product" value:products];
                [[TMSQLite shareInstance] query:sql];
                for (id product in products) {
                    sql = [self fromInsert:@"e360_product" data:product];
                    [[TMSQLite shareInstance] query:sql];
                }
            }
            [items setValue:nil forKey:@"product"];
            //
            NSDictionary *suit = [items objectForKey:@"suit"];
            if(isEmpty(suit)==NO) {
                NSString *sql = [self fromDelete:@"e360_mjt_suit" value:suit];
                [[TMSQLite shareInstance] query:sql];
                sql = [self fromInsert:@"e360_mjt_suit" data:suit];
                [[TMSQLite shareInstance] query:sql];
            }
            [items setValue:nil forKey:@"suit"];
            //
            NSArray *carts = [items allValues];
            if (carts) {
                NSString *sql = [self fromDelete:@"e360_cart" value:carts];
                [[TMSQLite shareInstance] query:sql];
                for (id item in carts) {
                    sql = [self fromInsert:@"e360_cart" data:item];
                    [[TMSQLite shareInstance] query:sql];
                }
            }
            [[[TMSQLite shareInstance] transaction] commit];
        }
    }
    //
    NSString *sql = @"SELECT * FROM e360_cart WHERE id>0";
    if ([data objectForKey:@"uuid"]) {
        sql = [sql stringByAppendingFormat:@" AND clientuuid='%@'", [data objectForKey:@"uuid"]];
    }
    //
    NSMutableDictionary *sid = [NSMutableDictionary dictionary];
    NSMutableDictionary *pid = [NSMutableDictionary dictionary];
    NSMutableArray *items = [[TMSQLite shareInstance] query:sql];
    for (id item in items) {
        id suitid = [item objectForKey:@"suitid"];
        if ([suitid isKindOfClass:NSNumber.class]) {
            [sid setValue:[NSNull null] forKey:suitid];
        }
        id productid = [item objectForKey:@"productid"];
        if ([productid isKindOfClass:NSNumber.class]) {
            [pid setValue:[NSNull null] forKey:productid];
        }
    }
    //
    NSMutableDictionary *arg = [NSMutableDictionary dictionary];
    [arg setValue:[pid.allKeys componentsJoinedByString:@","] forKey:@"productid"];
    //
    id products = nil;
    if ([pid count] > 0) {
        products = [self productDetail:[pid.allKeys componentsJoinedByString:@","]];
    }
    id suits = nil;
    if ([sid count] > 0) {
        suits = [[TMSQLite shareInstance] query:[NSString stringWithFormat:@"SELECT * FROM e360_mjt_suit WHERE id IN (%@)",[sid.allKeys componentsJoinedByString:@","]]];
    }
    for (id item in items) {
        if ([[item objectForKey:@"productid"] intValue] > 0) {
            for (id product in products) {
                if ([[product objectForKey:@"id"] isEqual:[item objectForKey:@"productid"]]) {
                    [item setValue:product forKey:@"product_detail"];
                    break;
                }
            }
            for (id suit in suits) {
                if ([[suit objectForKey:@"id"] isEqual:[item objectForKey:@"suitid"]]) {
                    [item setValue:suit forKey:@"suit"];
                    break;
                }
            }
        }else{
            id detail = [TMJSON parse:[item objectForKey:@"json"]];
            if (detail) {
                [detail setValue:[detail objectForKey:@"content"] forKey:@"remark"];
                [item setValue:detail forKey:@"product_detail"];
            }
        }
        [item setValue:nil forKey:@"json"];
    }
    return items;
}


//
+(id)userDeleteSale:(NSDictionary*)data{
    if ([[UIDevice currentDevice] network] != UIDeviceNetworkNone) {
        NSMutableDictionary *temp = [NSMutableDictionary dictionary];
        [temp setValue:[data objectForKey:@"uuid"] forKey:@"value"];
        [temp setValue:@"e360_sale" forKey:@"table"];
        [temp setValue:@"uuid" forKey:@"key"];
        //
        NSMutableArray *delete = [NSMutableArray array];
        [delete addObject:temp];
        //
        NSMutableDictionary *post = [NSMutableDictionary dictionary];
        [post setValue:[TMJSON stringify:delete] forKey:@"items"];
        //
        NSMutableString *request = [NSMutableString stringWithString:@"?n=api&a=user&c=other&m=general_del"];
        if ([self loadJson:request key:@"data" data:post]) {
            [self cacheData:data table:@"e360_sale" key:@"uuid" type:0];
            return data;
        }
    }
    return nil;
}
+(id)userEditSale:(NSDictionary*)data client:(id)client{
    if ([[UIDevice currentDevice] network] != UIDeviceNetworkNone) {
        CGFloat price = 0;
        NSInteger count = 0;
        NSMutableArray *cart = [NSMutableArray array];
        for (id item in [data objectForKey:@"cartarr"]) {
            id hardpacked = [item objectForKey:@"temp_hardpacked"];
            if (hardpacked == nil) {
                hardpacked = [item objectForKey:@"hardpacked"];
            }
            //
            NSMutableDictionary *temp = [NSMutableDictionary dictionary];
            [temp setValue:[[item objectForKey:@"product_detail"] objectForKey:@"remark"] forKey:@"remark"];
            [temp setValue:[[item objectForKey:@"product_detail"] objectForKey:@"price"] forKey:@"price"];
            [temp setValue:[item objectForKey:@"productid"] forKey:@"productid"];
            [temp setValue:[item objectForKey:@"matchid"] forKey:@"matchid"];
            [temp setValue:[item objectForKey:@"suitid"] forKey:@"suitid"];
            [temp setValue:[item objectForKey:@"number"] forKey:@"count"];
            [temp setValue:[item objectForKey:@"uuid"] forKey:@"uuid"];
            [temp setValue:hardpacked forKey:@"hardpacked"];
            [cart addObject:temp];
            //
            NSInteger p = [[temp objectForKey:@"price"] floatValue];
            NSInteger c = [[temp objectForKey:@"count"] intValue];
            price += c * p;
            count += c;
        }
        id address = [client objectForKey:@"address"];
        id areaname = [client objectForKey:@"areaname"];
        id cityname = [client objectForKey:@"cityname"];
        id provincename = [client objectForKey:@"provincename"];
        NSMutableArray *temps = [NSMutableArray array];
        if (provincename) {
            [temps addObject:provincename];
        }
        if (cityname) {
            [temps addObject:cityname];
        }
        if (areaname) {
            [temps addObject:areaname];
        }
        if (address) {
            [temps addObject:address];
        }
        //
        NSMutableDictionary *addressjson = [NSMutableDictionary dictionary];
        [addressjson setValue:[temps componentsJoinedByString:@" "] forKey:@"address"];
        [addressjson setValue:[client objectForKey:@"truename"] forKey:@"truename"];
        [addressjson setValue:[client objectForKey:@"mobile"] forKey:@"mobile"];
        [addressjson setValue:[client objectForKey:@"email"] forKey:@"email"];
        //
        NSMutableDictionary *temp = [NSMutableDictionary dictionary];
        [temp setValue:[client objectForKey:@"uuid"] forKey:@"clientuuid"];
        [temp setValue:[NSNumber numberWithInteger:count] forKey:@"number"];
        [temp setValue:[NSNumber numberWithFloat:price] forKey:@"saleprice"];
        [temp setValue:[TMJSON stringify:addressjson] forKey:@"addressjson"];
        [temp setValue:[data objectForKey:@"agreementjson"] forKey:@"agreementjson"];
        [temp setValue:[data objectForKey:@"invoicename"] forKey:@"invoicename"];
        [temp setValue:[data objectForKey:@"hasinvoice"] forKey:@"hasinvoice"];
        [temp setValue:[data objectForKey:@"payment"] forKey:@"payment"];
        [temp setValue:[data objectForKey:@"thedate"] forKey:@"thedate"];
        [temp setValue:[data objectForKey:@"money"] forKey:@"money"];
        [temp setValue:[data objectForKey:@"uuid"] forKey:@"uuid"];
        [temp setValue:[data objectForKey:@"desc"] forKey:@"desc"];
        [temp setValue:[TMJSON stringify:cart] forKey:@"cartarr"];
        [temp setValue:[data objectForKey:@"id"] forKey:@"id"];
        //
        NSMutableString *request = [NSMutableString stringWithString:@"?n=api&a=user&c=sale&m=add_"];
        if ([self loadJson:request key:nil data:temp]) {
            [self userDeleteCart:cart];
            return temp;
        }
    }
    return nil;
}
+(id)userSale:(id)data{
    if ([[UIDevice currentDevice] network] != UIDeviceNetworkNone) {
        NSMutableString *url = [NSMutableString stringWithString:@"?n=api&a=user&c=sale&m=index&detail=1"];
        for (id key in data) {
            id val = [data objectForKey:key];
            if (val && val != [NSNull null]) {
                [url appendFormat:@"&%@=%@", key, val];
            }else{
                [url appendFormat:@"&%@=", key];
            }
        }
        NSMutableDictionary *items = [self loadJson:url key:@"data" data:nil];
        if (items) {
            [[[TMSQLite shareInstance] transaction] begin];
            //
            NSString *sql = [self fromDelete:@"e360_sale" value:items];
            [[TMSQLite shareInstance] query:sql];
            for (id item in items) {
                sql = [self fromInsert:@"e360_sale" data:item];
                [[TMSQLite shareInstance] query:sql];
            }
            [[[TMSQLite shareInstance] transaction] commit];
        }
    }
    //
    NSString *sql = @"SELECT * FROM e360_sale WHERE deleted=0";
    if ([data objectForKey:@"clientuuid"]) {
        sql = [sql stringByAppendingFormat:@" AND clientuuid='%@'", [data objectForKey:@"clientuuid"]];
    }
    if ([data objectForKey:@"status"]) {
        sql = [sql stringByAppendingFormat:@" AND paystatus=%@", [data objectForKey:@"status"]];
    }
    sql = [sql stringByAppendingString:@" ORDER BY postdate DESC"];
    //
    if ([data objectForKey:@"page"] && [data objectForKey:@"limit"]) {
        int page = [[data objectForKey:@"page"] intValue] - 1;
        int limit = [[data objectForKey:@"limit"] intValue];
        sql = [sql stringByAppendingFormat:@" LIMIT %d, %d", page * limit, limit];
    }
    return [[TMSQLite shareInstance] query:sql];
}
//
+(id)userFavoriteKey:(NSDictionary*)data{
    if ([[data objectForKey:@"t"] isEqualToString:@"product"]) {
        NSMutableDictionary *result = [NSMutableDictionary dictionary];
        [result setValue:@"e360_user_favorite_product" forKey:@"table"];
        [result setValue:@"user_favorite_product" forKey:@"tableName"];
        [result setValue:@"productid" forKey:@"tableKey"];
        //
        [result setValue:@"e360_product" forKey:@"targetTable"];
        [result setValue:@"product" forKey:@"targetName"];
        [result setValue:@"" forKey:@"targetKey"];
        return result;
    }
    if ([[data objectForKey:@"t"] isEqualToString:@"scheme"]) {
        NSMutableDictionary *result = [NSMutableDictionary dictionary];
        [result setValue:@"e360_user_favorite_scheme" forKey:@"table"];
        [result setValue:@"user_favorite_scheme" forKey:@"tableName"];
        [result setValue:@"schemeid" forKey:@"tableKey"];
        //
        [result setValue:@"e360_scheme" forKey:@"targetTable"];
        [result setValue:@"scheme" forKey:@"targetName"];
        [result setValue:@"" forKey:@"targetKey"];
        return result;
    }
    if ([[data objectForKey:@"t"] isEqualToString:@"photo"]) {
        NSMutableDictionary *result = [NSMutableDictionary dictionary];
        [result setValue:@"e360_user_favorite_photo" forKey:@"table"];
        [result setValue:@"user_favorite_photo" forKey:@"tableName"];
        [result setValue:@"photoid" forKey:@"tableKey"];
        //
        [result setValue:@"e360_user_photo" forKey:@"targetTable"];
        [result setValue:@"user_photo" forKey:@"targetName"];
        [result setValue:@"" forKey:@"targetKey"];
        return result;
    }
    if ([[data objectForKey:@"t"] isEqualToString:@"match"]) {
        NSMutableDictionary *result = [NSMutableDictionary dictionary];
        [result setValue:@"e360_user_favorite_match" forKey:@"table"];
        [result setValue:@"user_favorite_match" forKey:@"tableName"];
        [result setValue:@"matchid" forKey:@"tableKey"];
        //
        [result setValue:@"e360_scheme_match" forKey:@"targetTable"];
        [result setValue:@"scheme_match" forKey:@"targetName"];
        [result setValue:@"" forKey:@"targetKey"];
        return result;
    }
    if ([[data objectForKey:@"t"] isEqualToString:@"suit"]) {
        NSMutableDictionary *result = [NSMutableDictionary dictionary];
        [result setValue:@"e360_user_favorite_suit" forKey:@"table"];
        [result setValue:@"user_favorite_suit" forKey:@"tableName"];
        [result setValue:@"suitid" forKey:@"tableKey"];
        //
        [result setValue:@", CASE IFNULL(a.pic,1) WHEN 1 THEN b.pic ELSE a.pic END pic, CASE IFNULL(a.json,1) WHEN 1 THEN b.json ELSE a.json END json" forKey:@"targetKey"];
        [result setValue:@"e360_mjt_suit" forKey:@"targetTable"];
        [result setValue:@"mjt_suit" forKey:@"targetName"];
        return result;
    }
    return nil;
}
+(id)userHaveFavorite:(NSDictionary*)data client:(id)client{
    if (client && [client objectForKey:@"uuid"]) {
        //取收藏
        static CGFloat time = 0;
        CGFloat curr = [[NSDate date] timeIntervalSince1970];
        if (curr - time > 1) {
            time = curr;
            //
            NSMutableDictionary *arg = [NSMutableDictionary dictionary];
            [arg setValue:[client objectForKey:@"uuid"] forKey:@"clientuuid"];
            [arg setValue:[data objectForKey:@"t"] forKey:@"t"];
            [arg setValue:@(NSNotFound) forKey:@"limit"];
            [AppData userFavoriteGet:arg];
        }
        //
        NSDictionary *result = [self userFavoriteKey:data];
        if (result && [data objectForKey:@"id"]) {
            NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@=%@ AND clientuuid='%@'", [result objectForKey:@"table"], [result objectForKey:@"tableKey"], [data objectForKey:@"id"], [client objectForKey:@"uuid"]];
            return [[[TMSQLite shareInstance] query:sql] firstObject];
        }
    }
    return nil;
}
+(id)userDeleteFavorite:(NSDictionary*)data client:(id)client{
    if (data && [data objectForKey:@"id"]) {
        NSDictionary *temp = [self userHaveFavorite:data client:client];
        if (temp) {
            NSDictionary *result = [self userFavoriteKey:data];
            if (result) {
                if (NO == [self cacheData:temp table:[result objectForKey:@"table"] key:@"uuid" type:0]) {
                    NSMutableDictionary *arg = [NSMutableDictionary dictionary];
                    [arg setValue:[client objectForKey:@"uuid"] forKey:@"clientuuid"];
                    [arg setValue:[data objectForKey:@"id"] forKey:@"id"];
                    [arg setValue:[data objectForKey:@"t"] forKey:@"t"];
                    //
                    NSMutableString *request = [NSMutableString stringWithString:@"?n=api&a=user&c=favorite&m=del"];
                    for (id key in [arg allKeys]) {
                        id val = [arg valueForKey:key];
                        [request appendFormat:@"&%@=%@", key, val];
                    }
                    if ([self loadJson:request key:nil data:arg]) {
                        return data;
                    }else{
                        return nil;
                    }
                }
                return data;
            }
        }
    }
    return nil;
}
+(id)userEditFavorite:(NSDictionary*)data client:(id)client{
    if (data && [data objectForKey:@"id"]) {
        NSDictionary *temp = [self userHaveFavorite:data client:client];
        if (temp == nil) {
            NSDictionary *result = [self userFavoriteKey:data];
            if (result) {
                NSString *tableKey = [result objectForKey:@"tableKey"];
                NSString *table = [result objectForKey:@"table"];
                //
                temp = [NSMutableDictionary dictionary];
                [temp setValue:[client objectForKey:@"uuid"] forKey:@"clientuuid"];
                [temp setValue:[data objectForKey:@"t"] forKey:@"t"];
                [temp setValue:[NSString uuid] forKey:@"uuid"];
                //post
                NSMutableDictionary *dat = nil;
                id pic = [data objectForKey:@"pic"];
                id json = [data objectForKey:@"json"];
                if (pic || json) {
                    dat = [NSMutableDictionary dictionary];
                    if (json && [json isKindOfClass:NSDictionary.class]) {
                        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                        for (id key in [json allKeys]) {
                            id val = [json objectForKey:key];
                            if (val) {
                                if ([val isKindOfClass:NSIndexPath.class]) {
                                    NSIndexPath *indexPath = val;
                                    [dic setValue:@{@"row":@(indexPath.row),@"section":@(indexPath.section)} forKey:[NSString stringWithFormat:@"%@",key]];
                                }
                                if ([val isKindOfClass:NSDictionary.class]) {
                                    NSMutableDictionary *dic2 = [NSMutableDictionary dictionary];
                                    for (id key2 in [val allKeys]) {
                                        id val2 = [val objectForKey:key2];
                                        if ([val2 isKindOfClass:NSIndexPath.class]) {
                                            NSIndexPath *indexPath = val2;
                                            [dic2 setValue:@{@"row":@(indexPath.row),@"section":@(indexPath.section)} forKey:[NSString stringWithFormat:@"%@",key2]];
                                        }
                                    }
                                    [dic setValue:dic2 forKey:[NSString stringWithFormat:@"%@",key]];
                                }
                            }
                        }
                        [dat setValue:[TMJSON stringify:dic] forKey:@"json"];
                    }
                    if (pic && [pic isKindOfClass:UIImage.class]) {
                        UIImage *thumb = [pic resize:CGSizeMake(400, 300)];
                        id path = [self cacheImage:thumb path:nil];
                        if (path) {
                            NSString *file = [NSString libraryAppend:path];
                            NSData *byte = [NSData dataWithContentsOfFile:file];
                            if (byte) {
                                NSString *data = [byte base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
                                [dat setValue:[path pathExtension] forKey:@"extname"];
                                [dat setValue:data forKey:@"picdata"];
                                [dat setValue:path forKey:@"path"];
                            }
                        }
                    }
                }
                //
                NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithDictionary:temp];
                [cache setValue:[data objectForKey:@"id"] forKey:tableKey];
                [cache setValue:[dat objectForKey:@"json"] forKey:@"json"];
                [cache setValue:[dat objectForKey:@"path"] forKey:@"pic"];
                //
                if (NO == [self cacheData:cache table:table key:@"uuid" type:1]) {
                    NSMutableString *request = [NSMutableString stringWithString:@"?n=api&a=user&c=favorite&m=add"];
                    NSMutableDictionary *arg = [NSMutableDictionary dictionaryWithDictionary:temp];
                    [arg setValue:[data objectForKey:@"id"] forKey:@"id"];
                    for (id key in [arg allKeys]) {
                        id val = [arg valueForKey:key];
                        [request appendFormat:@"&%@=%@", key, val];
                    }
                    if ([self loadJson:request key:nil data:dat]) {
                        return data;
                    }else{
                        return nil;
                    }
                }
                return data;
            }
        }
    }
    return nil;
}
+(id)userFavoriteGet:(NSDictionary*)data{
    if ([[UIDevice currentDevice] network] != UIDeviceNetworkNone) {
        NSDictionary *result = [self userFavoriteKey:data];
        if (result) {
            id targetTable = [result objectForKey:@"targetTable"];
            id table = [result objectForKey:@"table"];
            //
            NSMutableString *request = [NSMutableString stringWithString:@"?n=api&a=user&c=favorite"];
            for (id k in data) {
                id v = [data objectForKey:k];
                if (v && v != [NSNull null]) {
                    [request appendFormat:@"&%@=%@", k, v];
                }else{
                    [request appendFormat:@"&%@=", k];
                }
            }
            //
            id data = [self loadJson:request key:nil data:nil];
            if (data) {
                id relation = [data objectForKey:@"relation"];
                if ([relation isKindOfClass:NSDictionary.class]) {
                    id tableName = [result objectForKey:@"tableName"];
                    id targetName = [result objectForKey:@"targetName"];
                    //
                    id items = [relation objectForKey:tableName];
                    id values = [relation objectForKey:targetName];
                    [[TMSQLite shareInstance] query:[NSString stringWithFormat:@"DELETE FROM %@", table]];
                    if (items || values) {
                        [[[TMSQLite shareInstance] transaction] begin];
                        for (id item in items) {
                            NSString *sql = [self fromInsert:table data:item];
                            [[TMSQLite shareInstance] query:sql];
                        }
                        for (id value in values) {
                            NSString *sql = [self fromInsert:targetTable data:value];
                            [[TMSQLite shareInstance] query:sql];
                        }
                        [[[TMSQLite shareInstance] transaction] commit];
                    }
                }
            }
        }
    }
    return nil;
}
+(id)userFavorite:(NSDictionary*)data{
    NSDictionary *result = [self userFavoriteKey:data];
    if (result) {
        id targetTable = [result objectForKey:@"targetTable"];
        id targetKey = [result objectForKey:@"targetKey"];
        id tableKey = [result objectForKey:@"tableKey"];
        id table = [result objectForKey:@"table"];
        //取收藏
        static CGFloat time = 0;
        CGFloat curr = [[NSDate date] timeIntervalSince1970];
        if (curr - time > 1) {
            time = curr;
            //
            NSMutableDictionary *arg = [NSMutableDictionary dictionary];
            [arg setValue:[data objectForKey:@"clientuuid"] forKey:@"clientuuid"];
            [arg setValue:[data objectForKey:@"limit"] forKey:@"limit"];
            [arg setValue:[data objectForKey:@"page"] forKey:@"page"];
            [arg setValue:[data objectForKey:@"t"] forKey:@"t"];
            [AppData userFavoriteGet:arg];
        }
        //
        NSString *sql = [NSString stringWithFormat:@"SELECT b.*, a.uuid AS favoriteuuid %@ FROM %@ AS b, %@ AS a WHERE a.deleted=0 AND b.deleted=0 AND a.%@=b.id", targetKey, targetTable, table, tableKey];
        if ([data objectForKey:@"clientuuid"]) {
            sql = [sql stringByAppendingFormat:@" AND a.clientuuid='%@'", [data objectForKey:@"clientuuid"]];
        }
        if ([data objectForKey:@"keyword"]) {
            id keyword = [data objectForKey:@"keyword"];
            if ([[data objectForKey:@"t"] isEqualToString:@"product"]) {
                sql = [sql stringByAppendingFormat:@" AND (b.productname like '%%%@%%' OR b.productsn like '%%%@%%')", keyword, keyword];
            }
            if ([[data objectForKey:@"t"] isEqualToString:@"scheme"]) {
                sql = [sql stringByAppendingFormat:@" AND (b.schemename like '%%%@%%' OR b.housesn like '%%%@%%')", keyword, keyword];
            }
            if ([[data objectForKey:@"t"] isEqualToString:@"match"]) {
                sql = [sql stringByAppendingFormat:@" AND (b.matchname like '%%%@%%' OR b.author like '%%%@%%')", keyword, keyword];
            }
            if ([[data objectForKey:@"t"] isEqualToString:@"suit"]) {
                sql = [sql stringByAppendingFormat:@" AND (b.suitname like '%%%@%%' OR b.suitsn like '%%%@%%')", keyword, keyword];
            }
            if ([[data objectForKey:@"t"] isEqualToString:@"photo"]) {
                sql = [sql stringByAppendingFormat:@" AND (b.photoname like '%%%@%%')", keyword];
            }
        }
        if ([data objectForKey:@"page"] && [data objectForKey:@"limit"]) {
            int limit = [[data objectForKey:@"limit"] intValue];
            int page = [[data objectForKey:@"page"] intValue] - 1;
            sql = [sql stringByAppendingFormat:@" LIMIT %d, %d", page * limit, limit];
        }
        return [[TMSQLite shareInstance] query:sql];
    }
    return nil;
}


//
+(id)userMatchChild:(NSArray*)data parentid:(id)parentid{
    NSMutableArray *temp = [NSMutableArray array];
    for (id item in data) {
        if ([[item objectForKey:@"parentid"] isEqual:parentid]) {
            [temp addObject:item];
            //
            id child = [self userMatchChild:data parentid:[item objectForKey:@"id"]];
            if (child) {
                [item setValue:child forKey:@"child"];
            }
        }
    }
    if ([temp count] > 0) {
        return temp;
    }
    return nil;
}
+(id)userMatchCate{
    if ([[UIDevice currentDevice] network] != UIDeviceNetworkNone) {
        static CGFloat time = 0;
        CGFloat curr = [[NSDate date] timeIntervalSince1970];
        if (curr - time > 1) {
            time = curr;
            //
            NSArray *temps = [self loadJson:@"?n=api&a=scheme&c=match&m=cate" key:@"categories" data:nil];
            if (temps) {
                [[[TMSQLite shareInstance] transaction] begin];
                [[TMSQLite shareInstance] query:@"DELETE FROM e360_scheme_match_class"];
                for (id temp in temps) {
                    NSString *sql = [self fromInsert:@"e360_scheme_match_class" data:temp];
                    [[TMSQLite shareInstance] query:sql];
                }
                [[[TMSQLite shareInstance] transaction] commit];
            }
        }
    }
    return nil;
}
+(id)userMatchScreen:(id)pid{
    [self userMatchCate];
    //
    NSString *sql = @"SELECT *, classname As name FROM e360_scheme_match_class WHERE deleted=0 ORDER BY sort ASC";
    NSMutableArray *data = [[TMSQLite shareInstance] query:sql];
    NSArray *items = [self userMatchChild:data parentid:[NSNumber numberWithInt:0]];
    NSMutableDictionary *temp = [NSMutableDictionary dictionary];
    [temp setValue:items forKey:@"child"];
    [temp setValue:@"筛选" forKey:@"name"];
    return temp;
}
+(id)userDeleteMatch:(id)data{
    NSMutableArray *temps = [NSMutableArray array];
    if ([data isKindOfClass:NSArray.class]) {
        for (id item in data) {
            if ([item isKindOfClass:NSDictionary.class]) {
                [temps addObject:item];
            }
        }
    }
    if ([data isKindOfClass:NSDictionary.class]) {
        [temps addObject:data];
    }
    //
    if (NO == [self cacheData:temps table:@"e360_scheme_match" key:@"uuid" type:0]) {
        NSMutableArray *ids = [NSMutableArray array];
        for (id item in temps) {
            id iid = [item objectForKey:@"uuid"];
            if (iid) {
                [ids addObject:iid];
            }
        }
        //
        NSString *request = [NSString stringWithFormat:@"?n=api&a=scheme&c=match&m=del&uuid=%@", [ids componentsJoinedByString:@","]];
        if ([self loadJson:request key:@"data" data:nil]) {
            return data;
        }else{
            return nil;
        }
    }
    return data;
}
+(id)userShareMatch:(NSDictionary*)data{
    [data setValue:[NSNumber numberWithBool:YES] forKey:@"isshare"];
    //
    if (NO == [self cacheData:data table:@"e360_scheme_match" key:@"uuid" type:1]) {
        NSString *request = [NSString stringWithFormat:@"?n=api&a=scheme&c=match&m=share&uuid=%@", [data objectForKey:@"uuid"]];
        if ([self loadJson:request key:@"data" data:nil]) {
            return data;
        }else{
            return nil;
        }
    }
    return data;
}
+(id)userEditMatch:(NSDictionary*)data bitmap:(UIImage*)bitmap{
    NSString *uuid = [data objectForKey:@"uuid"];
    if (uuid == nil) {
        uuid = [NSString uuid];
        [data setValue:uuid forKey:@"uuid"];
    }
    //
    id author = [data objectForKey:@"author"];
    if (author == nil) {
        id user = [TMGlobal valueForKey:@"user"];
        [data setValue:[user objectForKey:@"id"] forKey:@"userid"];
        [data setValue:[user objectForKey:@"truename"] forKey:@"author"];
        [data setValue:[user objectForKey:@"companyid"] forKey:@"companyid"];
    }
    //
    UIImage *image = [data objectForKey:@"bitmap"];
    if (image && [image isKindOfClass:UIImage.class]) {
        NSString *pic = [data objectForKey:@"pic"];
        NSString *path = [self cacheImage:image path:pic];
        if (path) {
            [data setValue:path forKey:@"pic"];
        }
    }
    //
    NSMutableDictionary *temp = [NSMutableDictionary dictionaryWithDictionary:data];
    [temp setValue:[TMJSON stringify:[data objectForKey:@"json"]] forKey:@"json"];
    if (NO == [self cacheData:temp table:@"e360_scheme_match" key:@"uuid" type:1]) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:base64Encoded([temp objectForKey:@"json"]) forKey:@"json"];
        [dic setValue:[temp objectForKey:@"clientuuid"] forKey:@"clientuuid"];
        [dic setValue:[temp objectForKey:@"companyid"] forKey:@"companyid"];
        [dic setValue:[temp objectForKey:@"matchname"] forKey:@"matchname"];
        [dic setValue:[temp objectForKey:@"classids"] forKey:@"classids"];
        [dic setValue:[temp objectForKey:@"length"] forKey:@"length"];
        [dic setValue:[temp objectForKey:@"height"] forKey:@"height"];
        [dic setValue:[temp objectForKey:@"author"] forKey:@"author"];
        [dic setValue:[temp objectForKey:@"width"] forKey:@"width"];
        [dic setValue:[temp objectForKey:@"price"] forKey:@"price"];
        [dic setValue:[temp objectForKey:@"desc"] forKey:@"desc"];
        [dic setValue:[temp objectForKey:@"uuid"] forKey:@"uuid"];
        [dic setValue:[temp objectForKey:@"id"] forKey:@"id"];
        //
        if (image && [image isKindOfClass:UIImage.class]) {
            NSString *base = [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
            [dic setValue:base forKey:@"pic"];
        }
        //
        if ([self loadJson:@"?n=api&a=scheme&c=match&m=edit" key:@"data" data:dic]) {
            return data;
        }
        return nil;
    }
    //
    NSMutableArray *classids = [NSMutableArray array];
    NSArray *cids = [[temp objectForKey:@"classids"] componentsSeparatedByString:@","];
    for (id cid in cids) {
        NSMutableDictionary *tmp = [NSMutableDictionary dictionary];
        [tmp setValue:[temp objectForKey:@"id"] forKey:@"matchid"];
        [tmp setValue:[NSString uuid] forKey:@"uuid"];
        [tmp setValue:cid forKey:@"classid"];
        [classids addObject:tmp];
    }
    [self cacheData:classids table:@"e360_scheme_match_detail" key:@"uuid" type:1];
    return data;
}
+(id)userMatch:(NSDictionary*)data{
    [self userMatchCate];
    //
    if ([[UIDevice currentDevice] network] != UIDeviceNetworkNone) {
        NSMutableString *request = [NSMutableString stringWithString:@"?n=api&a=scheme&c=match&m=index"];
        for (id key in data) {
            id val = [data objectForKey:key];
            if (val && val != [NSNull null]) {
                [request appendFormat:@"&%@=%@", key, val];
            }else{
                [request appendFormat:@"&%@=", key];
            }
        }
        NSArray *items = [self loadJson:request key:@"projects" data:nil];
        if (items) {
            [[[TMSQLite shareInstance] transaction] begin];
            //
            NSString *sql = [self fromDelete:@"e360_scheme_match" value:items];
            [[TMSQLite shareInstance] query:sql];
            for (id item in items) {
                id classids = [item objectForKey:@"classids"];
                for (id cid in classids) {
                    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                    [dic setValue:[item objectForKey:@"id"] forKey:@"matchid"];
                    [dic setValue:cid forKey:@"classid"];
                    //
                    sql = [self fromInsert:@"e360_scheme_match_detail" data:dic];
                    [[TMSQLite shareInstance] query:sql];
                }
                //
                sql = [self fromInsert:@"e360_scheme_match" data:item];
                [[TMSQLite shareInstance] query:sql];
            }
            [[[TMSQLite shareInstance] transaction] commit];
        }
    }
    //
    NSString *sql = @"SELECT *,(SELECT ''||group_concat(classid)||'' FROM e360_scheme_match_detail WHERE matchid=e360_scheme_match.id) classids FROM e360_scheme_match WHERE deleted=0";
    if ([data objectForKey:@"clientuuid"]) {
        sql = [sql stringByAppendingFormat:@" AND clientuuid='%@'", [data objectForKey:@"clientuuid"]];
    }
    //
    if ([data objectForKey:@"cateid"]) {
        NSArray *cate = [[TMSQLite shareInstance] query:@"SELECT * FROM e360_product_cate WHERE deleted=0"];
        NSArray *cids = [self getAllChildId:cate parentid:[data objectForKey:@"cateid"]];
        if (cids) {
            sql = [sql stringByAppendingFormat:@" AND cateid IN (%@)", [cids componentsJoinedByString:@","]];
        }
    }
    //
    if ([data objectForKey:@"styleid"]) {
        sql = [sql stringByAppendingFormat:@" AND (','||classids||',') LIKE '%%,%@,%%'", [data objectForKey:@"styleid"]];
    }
    if ([data objectForKey:@"spaceid"]) {
        sql = [sql stringByAppendingFormat:@" AND (','||classids||',') LIKE '%%,%@,%%'", [data objectForKey:@"spaceid"]];
    }
    if ([data objectForKey:@"colorid"]) {
        sql = [sql stringByAppendingFormat:@" AND (','||classids||',') LIKE '%%,%@,%%'", [data objectForKey:@"colorid"]];
    }
    //
    id user = [TMGlobal valueForKey:@"user"];
    if (user) {
        sql = [sql stringByAppendingFormat:@" AND companyid=%@", [user objectForKey:@"companyid"]];
    }
    //
    if ([data objectForKey:@"isshare"]) {
        if ([[data objectForKey:@"isshare"] intValue] > 0) {
            sql = [sql stringByAppendingString:@" AND isshare=1 AND verify=1"];
        }else{
            if (user) {
                sql = [sql stringByAppendingFormat:@" AND userid=%@", [user objectForKey:@"id"]];
            }
        }
    }
    //
    if ([data objectForKey:@"keyword"]) {
        id keyword = [data objectForKey:@"keyword"];
        sql = [sql stringByAppendingFormat:@" AND (matchname like '%%%@%%' OR author like '%%%@%%')", keyword, keyword];
    }
    //
    if ([data objectForKey:@"sort"]) {
        NSArray *sort = [[data objectForKey:@"sort"] componentsSeparatedByString:@"|"];
        if (sort.count == 2) {
            sql = [sql stringByAppendingFormat:@" ORDER BY %@ %@", [sort firstObject], [sort lastObject]];
        }else{
            sql = [sql stringByAppendingString:@" ORDER BY id ASC"];
        }
    }else{
        sql = [sql stringByAppendingString:@" ORDER BY id ASC"];
    }
    if ([data objectForKey:@"page"] && [data objectForKey:@"limit"]) {
        int limit = [[data objectForKey:@"limit"] intValue];
        int page = [[data objectForKey:@"page"] intValue] - 1;
        sql = [sql stringByAppendingFormat:@" LIMIT %d, %d", page * limit, limit];
    }
    return [[TMSQLite shareInstance] query:sql];
}
+(id)userMatchDetail:(id)mid{
    [self userMatchCate];
    //
    NSString *sql = [NSString stringWithFormat:@"SELECT *,(SELECT ''||group_concat(classid)||'' FROM e360_scheme_match_detail WHERE matchid=e360_scheme_match.id) classids FROM e360_scheme_match WHERE id IN (%@)", mid];
    NSArray *temps = [[TMSQLite shareInstance] query:sql];
    for (id temp in temps) {
        sql = [NSString stringWithFormat:@"SELECT DISTINCT a.*, c.classname AS parentName FROM e360_scheme_match_class a, e360_scheme_match_detail b, e360_scheme_match_class c WHERE a.deleted=0 AND c.id=a.parentid AND a.id=b.classid AND b.matchid=%@", mid];
        NSArray *items = [[TMSQLite shareInstance] query:sql];
        //
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        for (id item in items) {
            id key = [item objectForKey:@"parentName"];
            if (isEmpty(key) == NO) {
                NSMutableArray *val = [dic objectForKey:key];
                if (val == nil) {
                    val = [NSMutableArray array];
                    [dic setValue:val forKey:key];
                }
                id name = [item objectForKey:@"classname"];
                if (isEmpty(name) == NO) {
                    [val addObject:name];
                }
            }
        }
        //
        NSMutableArray *cov = [NSMutableArray array];
        for (id key in dic.allKeys) {
            NSMutableDictionary *tmp = [NSMutableDictionary dictionary];
            [tmp setValue:[dic objectForKey:key] forKey:@"values"];
            [tmp setValue:key forKey:@"name"];
            [cov addObject:tmp];
        }
        //
        [temp setValue:cov forKey:@"class"];
    }
    return temps;
}
+(id)userMatchResourceCate{
    NSMutableArray *items = [NSMutableArray array];
    [items addObject:@{@"name" : @"所有素材", @"id" : @"0", @"icon" : @"icon_All_nor.png"}];
    [items addObject:@{@"name" : @"背景", @"id" : @"1", @"icon" : @"icon_Background_nor.png"}];
    [items addObject:@{@"name" : @"色块", @"id" : @"2", @"icon" : @"icon_Color_nor.png"}];
    [items addObject:@{@"name" : @"形状", @"id" : @"3", @"icon" : @"icon_Shape_nor.png"}];
    [items addObject:@{@"name" : @"光效", @"id" : @"4", @"icon" : @"icon_Effect_nor.png"}];
    //
    NSMutableDictionary *temp = [NSMutableDictionary dictionary];
    [temp setValue:@"其他素材" forKey:@"name"];
    [temp setValue:items forKey:@"child"];
    return temp;
}
+(id)userMatchResource:(NSDictionary*)data{
    if ([[UIDevice currentDevice] network] != UIDeviceNetworkNone) {
        NSMutableString *index = [NSMutableString stringWithString:@"?n=api&a=scheme&c=scheme_resource&m=index"];
        for (id key in data) {
            id val = [data objectForKey:key];
            if (val && val != [NSNull null]) {
                [index appendFormat:@"&%@=%@", key, val];
            }else{
                [index appendFormat:@"&%@=", key];
            }
        }
        NSArray *items = [self loadJson:index key:@"data" data:nil];
        if (items) {
            [[[TMSQLite shareInstance] transaction] begin];
            for (id item in items) {
                NSString *sql = [self fromInsert:@"e360_scheme_resource" data:item];
                [[TMSQLite shareInstance] query:sql];
            }
            [[[TMSQLite shareInstance] transaction] commit];
        }
    }
    //
    NSString *sql = @"SELECT * FROM e360_scheme_resource WHERE deleted=0";
    if ([data objectForKey:@"type"]) {
        sql = [sql stringByAppendingFormat:@" AND type =%@", [data objectForKey:@"type"]];
    }
    if ([data objectForKey:@"keyword"]) {
        sql = [sql stringByAppendingFormat:@" AND name LIKE '%%%@%%'", [data objectForKey:@"keyword"]];
    }
    if ([data objectForKey:@"page"] && [data objectForKey:@"limit"]) {
        int limit = [[data objectForKey:@"limit"] intValue];
        int page = [[data objectForKey:@"page"] intValue] - 1;
        sql = [sql stringByAppendingFormat:@" LIMIT %d, %d", page * limit, limit];
    }
    return [[TMSQLite shareInstance] query:sql];
}
+(id)userMatchAsset:(NSDictionary*)data{
    if ([[UIDevice currentDevice] network] != UIDeviceNetworkNone) {
        NSMutableString *index = [NSMutableString stringWithString:@"?n=api&a=user&c=photo"];
        for (id key in data) {
            id val = [data objectForKey:key];
            if (val && val != [NSNull null]) {
                [index appendFormat:@"&%@=%@", key, val];
            }else{
                [index appendFormat:@"&%@=", key];
            }
        }
        //
        NSArray *items = [self loadJson:index key:@"data" data:nil];
        if (items) {
            [[[TMSQLite shareInstance] transaction] begin];
            for (id item in items) {
                NSString *sql = [self fromInsert:@"e360_user_photo" data:item];
                [[TMSQLite shareInstance] query:sql];
            }
            [[[TMSQLite shareInstance] transaction] commit];
        }
    }
    //
    NSString *sql = @"SELECT * FROM e360_user_photo WHERE deleted=0";
    NSMutableArray *source = [NSMutableArray array];
    if ([data objectForKey:@"keyword"]) {
        sql = [sql stringByAppendingFormat:@" AND photoname LIKE '%%%@%%'", [data objectForKey:@"keyword"]];
    }else{
        NSArray *directory = [self userMatchAssetDirectory:data];
        [source addObjectsFromArray:directory];
        //
        if ([data objectForKey:@"dirid"]) {
            sql = [sql stringByAppendingFormat:@" AND dirid=%@", [data objectForKey:@"dirid"]];
        }else{
            sql = [sql stringByAppendingString:@" AND dirid=0"];
        }
    }
    //
    NSArray *asset = [[TMSQLite shareInstance] query:sql];
    [source addObjectsFromArray:asset];
    return source;
}
+(id)userMatchAssetEdit:(id)data{
    id dirid = [data objectForKey:@"parentid"];
    if (dirid == nil) {
        id dir = [self userMatchAssetDirectoryEdit:data];
        if (dir) {
            dirid = [dir objectForKey:@"id"];
        }
    }
    if ([[UIDevice currentDevice] network] != UIDeviceNetworkNone) {
        if ([data objectForKey:@"file"]) {
            id file = [data objectForKey:@"file"];
            id image = [file objectForKey:@"image"];
            if ([image isKindOfClass:UIImage.class]) {
                id thumb = [image resize:CGSizeMake(1024, 1024)];
                id base64 = [UIImagePNGRepresentation(thumb) base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
                //
                NSMutableDictionary *post = [NSMutableDictionary dictionary];
                [post setValue:[file objectForKey:@"name"] forKey:@"photoname"];
                [post setValue:base64 forKey:@"picdata"];
                [post setValue:dirid forKey:@"dirid"];
                //
                id item = [self loadJson:@"?n=api&a=user&c=photo&m=add" key:@"data" data:post];
                if (item) {
                    return item;
                }
            }
        }
    }
    return nil;
}
+(id)userMatchAssetDirectory:(NSDictionary*)data{
    if ([[UIDevice currentDevice] network] != UIDeviceNetworkNone) {
        NSArray *dirs = [self loadJson:@"?n=api&a=user&c=photo_dir" key:@"data" data:nil];
        if (dirs) {
            [[[TMSQLite shareInstance] transaction] begin];
            for (id dir in dirs) {
                NSString *sql = [self fromInsert:@"e360_user_photo_dir" data:dir];
                [[TMSQLite shareInstance] query:sql];
            }
            [[[TMSQLite shareInstance] transaction] commit];
        }
    }
    //
    NSString *sql = @"SELECT *,1 AS isDir FROM e360_user_photo_dir WHERE deleted=0";
    if ([data objectForKey:@"dirid"]) {
        sql = [sql stringByAppendingFormat:@" AND parentid=%@", [data objectForKey:@"dirid"]];
    }else{
        sql = [sql stringByAppendingString:@" AND parentid=0"];
    }
    return [[TMSQLite shareInstance] query:sql];
}
+(id)userMatchAssetDirectoryEdit:(id)data{
    if ([[UIDevice currentDevice] network] != UIDeviceNetworkNone) {
        id aid = [data objectForKey:@"id"];
        if (aid == nil) {
            NSMutableDictionary *post = [NSMutableDictionary dictionary];
            [post setValue:[data objectForKey:@"dirname"] forKey:@"dirname"];
            [post setValue:[data objectForKey:@"parentid"] forKey:@"parentid"];
            //
            id item = [self loadJson:@"?n=api&a=user&c=photo_dir&m=add" key:nil data:post];
            if (item) {
                [data setValue:[NSNumber numberWithBool:YES] forKey:@"isDir"];
                [data setValue:[item objectForKey:@"id"] forKey:@"id"];
                return data;
            }
        }
    }
    return nil;
}

//
+(id)userSchemeSpace:(id)pid{
    [self userMatchCate];
    //
    NSString *sql = @"SELECT * FROM e360_scheme_match_class WHERE deleted=0 AND parentid=(SELECT id FROM e360_scheme_match_class WHERE deleted=0 AND (parentid=0 OR parentid ISNULL) AND classname='空间') ORDER BY sort DESC";
    return [[TMSQLite shareInstance] query:sql];
}
+(id)userDeleteScheme:(id)data{
    NSMutableArray *temps = [NSMutableArray array];
    if ([data isKindOfClass:NSArray.class]) {
        for (id item in data) {
            if ([item isKindOfClass:NSDictionary.class]) {
                [temps addObject:item];
            }
        }
    }
    if ([data isKindOfClass:NSDictionary.class]) {
        [temps addObject:data];
    }
    //
    if (NO == [self cacheData:temps table:@"e360_scheme" key:@"uuid" type:0]) {
        NSMutableArray *ids = [NSMutableArray array];
        for (id item in temps) {
            id iid = [item objectForKey:@"uuid"];
            if (iid) {
                [ids addObject:iid];
            }
        }
        //
        NSString *request = [NSString stringWithFormat:@"?n=api&a=scheme&c=scheme&m=del&uuid=%@", [ids componentsJoinedByString:@","]];
        if ([self loadJson:request key:@"data" data:nil]) {
            return data;
        }else{
            return nil;
        }
    }
    return data;
}
+(id)userEditScheme:(NSDictionary*)data bitmap:(UIImage*)bitmap{
    id uuid = [data objectForKey:@"uuid"];
    if (uuid == nil) {
        [data setValue:[NSString uuid] forKey:@"uuid"];
    }
    //
    id author = [data objectForKey:@"author"];
    if (author == nil) {
        id user = [TMGlobal valueForKey:@"user"];
        [data setValue:[user objectForKey:@"id"] forKey:@"userid"];
        [data setValue:[user objectForKey:@"truename"] forKey:@"author"];
        [data setValue:[user objectForKey:@"companyid"] forKey:@"companyid"];
    }
    //
    if (NO == [self cacheData:data table:@"e360_scheme" key:@"uuid" type:1]) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:[TMJSON stringify:[data objectForKey:@"json"]] forKey:@"json"];
        [dic setValue:[data objectForKey:@"clientuuid"] forKey:@"clientuuid"];
        [dic setValue:[data objectForKey:@"companyid"] forKey:@"companyid"];
        [dic setValue:[data objectForKey:@"schemename"] forKey:@"name"];
        [dic setValue:[data objectForKey:@"price"] forKey:@"price"];
        [dic setValue:[data objectForKey:@"uuid"] forKey:@"uuid"];
        //
        id image = [data objectForKey:@"picdata"];
        if (image) {
            NSString *base = [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
            [dic setValue:base forKey:@"picdata"];
        }
        //
        if (uuid == nil) {
            if ([self loadJson:@"?n=api&a=scheme&c=scheme&m=add" key:@"data" data:dic]) {
                return data;
            }else{
                return nil;
            }
        }else{
            if ([self loadJson:[NSString stringWithFormat:@"?n=api&a=scheme&c=scheme&m=edit&uuid=%@", uuid] key:nil data:dic]) {
                return data;
            }else{
                return nil;
            }
        }
    }
    return data;
}
+(id)userScheme:(NSDictionary*)data{
    if ([[UIDevice currentDevice] network] != UIDeviceNetworkNone) {
        if ([data objectForKey:@"page"] && [[data objectForKey:@"page"] intValue] == 1) {
            NSArray *temps = [self loadJson:@"?n=api&a=scheme&c=scheme&m=cate" key:@"categories" data:nil];
            if (temps) {
                [[[TMSQLite shareInstance] transaction] begin];
                for (id temp in temps) {
                    NSString *sql = [self fromInsert:@"e360_scheme_class" data:temp];
                    [[TMSQLite shareInstance] query:sql];
                }
                [[[TMSQLite shareInstance] transaction] commit];
            }
        }
        //
        NSMutableString *index = [NSMutableString stringWithString:@"?n=api&a=scheme&c=scheme&m=index"];
        for (id key in data) {
            id val = [data objectForKey:key];
            if (val && val != [NSNull null]) {
                [index appendFormat:@"&%@=%@", key, val];
            }else{
                [index appendFormat:@"&%@=", key];
            }
        }
        NSArray *items = [self loadJson:index key:@"projects" data:nil];
        if (items) {
            NSString *sql = [self fromDelete:@"e360_scheme" value:items];
            [[TMSQLite shareInstance] query:sql];
            //
            [[[TMSQLite shareInstance] transaction] begin];
            for (id item in items) {
                sql = [self fromInsert:@"e360_scheme" data:item];
                [[TMSQLite shareInstance] query:sql];
            }
            [[[TMSQLite shareInstance] transaction] commit];
        }
    }
    //
    NSString *sql = @"SELECT * FROM e360_scheme WHERE deleted=0";
    if ([data objectForKey:@"clientuuid"]) {
        sql = [sql stringByAppendingFormat:@" AND clientuuid='%@'", [data objectForKey:@"clientuuid"]];
    }
    //
    id user = [TMGlobal valueForKey:@"user"];
    if (user) {
        sql = [sql stringByAppendingFormat:@" AND companyid=%@", [user objectForKey:@"companyid"]];
    }
    //
    if ([data objectForKey:@"isshare"]) {
        int isshare = [[data objectForKey:@"isshare"] intValue];
        if (isshare > 0) {
            sql = [sql stringByAppendingString:@" AND isshare=1"];
        }else{
            if (user) {
                sql = [sql stringByAppendingFormat:@" AND userid=%@", [user objectForKey:@"id"]];
            }
        }
    }
    //
    if ([data objectForKey:@"keyword"]) {
        id keyword = [data objectForKey:@"keyword"];
        sql = [sql stringByAppendingFormat:@" AND (schemename like '%%%@%%' OR author like '%%%@%%')", keyword, keyword];
    }
    sql = [sql stringByAppendingString:@" GROUP BY id"];
    //
    if ([data objectForKey:@"sort"]) {
        NSArray *sort = [[data objectForKey:@"sort"] componentsSeparatedByString:@"%7C"];
        if (sort.count == 2) {
            sql = [sql stringByAppendingFormat:@" ORDER BY %@ %@", [sort firstObject], [sort lastObject]];
        }
    }else{
        sql = [sql stringByAppendingString:@" ORDER BY id DESC"];
    }
    if ([data objectForKey:@"page"] && [data objectForKey:@"limit"]) {
        int limit = [[data objectForKey:@"limit"] intValue];
        int page = [[data objectForKey:@"page"] intValue] - 1;
        sql = [sql stringByAppendingFormat:@" LIMIT %d, %d", page * limit, limit];
    }
    return [[TMSQLite shareInstance] query:sql];
}

//
+(BOOL)userDeletePlan:(NSDictionary*)data{
    return NO;
}
+(id)userPlan:(NSDictionary*)data{
    return [NSMutableArray array];
}
@end